# coding=utf-8
import pickle
import sys

method = sys.argv[1]

if method == 'r':
    category = sys.argv[2]
    item = sys.argv[3]

'''
密码管理器

* 保存密码
* 获取密码

格式：
 * 密码 title
 * {"title": "passwd"}

分类：
 * web
 * 服务器

格式：
 {
 "web":{"jingfeng":"123456", "zhihu":"123456"}
 }
 title | passwd | url

自动生成安全密码 （用户可以输入长度）
'''

class PassWord:
    
    def __init__(self, title, user, passwd):
        self.title = title
        self.user = user
        self.passwd = passwd

class WebPassWord(PassWord):

    def __init__(self, title, user, passwd, url):
        super().__init__(title, user, passwd)
        self.url = url

    @classmethod
    def get_item(self):
        return ['title', 'user', 'passwd', 'url']

def select_db():
    with open('zpass.pass', 'rb') as f:
        return pickle.load(f)

def insert_db(obj):
    with open('zpass.pass', 'wb') as f:
        pickle.dump(obj, f)

def get_passwd():
    passwd =  select_db()
    return passwd[category].get(item)

def save_passwd(category, **kwargs):
    '''
    {'title': 'test', 'user': 'test', 'passwd': '123456', 'url': 'url.com'}
    |
    V
    {
        'web':{'title':
                {
                    user:test, 
                    passwd:123456, 
                    url:jingfeng.com
                }
            }
    }
    '''
    pwd_data = select_db() if select_db() else {}
    title = kwargs.pop('title')
    if not pwd_data:
        pwd_data[category] = {}
        pwd_data[category][title] = kwargs
    pwd_data[category][title] = kwargs
    print(pwd_data)
    insert_db(pwd_data)
    return True


def main():
    if method == 'r':
        print(get_passwd())
    elif method == 'w':
        user_choice = input("1 web, 2 server, 0 退出")
        passwd_args = {}
        if user_choice == '1':
            for i in WebPassWord.get_item():
                passwd_args[i] = input(i + ":")
        sp_stat = save_passwd(category='web', **passwd_args)
        if sp_stat is False:
            print('保存失败！')
        print('保存成功！')
        if user_choice == '2':
            pass


if __name__ == '__main__':
    main()



